<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- 引入公用JSP --%>
<%@ include file="/WEB-INF/include/taglib.jsp"%>
<%-- 加入自定义UI标签库 --%>
<%@ taglib prefix="sys" tagdir="/WEB-INF/tags/sys" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- EasyUI -->
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/ExpandIcon.css">
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/locale/easyui-lang-zh_CN.js"></script>
<title>用户角色菜单权限管理</title>
</head>
<body id="layout001" class="easyui-layout" data-options="fit:true,border:false">
    <!--  页面右部 -->
    <div id="orgPanel" data-options="region:'west',title:'机构',split:true,collapsible:false,minWidth:120,maxWidth:180,border:true">
        <!-- 组织机构树 -->
        <ul id="orgTree"></ul>
    </div>

    <!-- 页面中部 -->
    <div data-options="region:'center',fit:false,border:false">
        <div id="layout002" class="easyui-layout" data-options="fit:true,border:false">
            <!--  页面右部 -->
            <div id="userPanel" data-options="region:'west',title:'用户',split:true,collapsible:false,minWidth:120,maxWidth:180,border:true">
                <!-- 组织机构下的用户列表 -->
                <table id="userTable" class="easyui-datagrid" data-options="border:false,fit:true">
                    <thead>
                        <tr>
                            <th data-options="field:'name',width:150,align:'left'">姓名</th>
                        </tr>
                    </thead>
                </table>
            </div>
            
            <!-- 页面中部 -->
            <div data-options="region:'center',fit:false,border:false">
                <div id="layout003" class="easyui-layout" data-options="fit:true,border:false">
                    <!--  页面右部 -->
                    <div id="rolePanel" data-options="region:'west',title:'角色',split:true,collapsible:false,minWidth:120,maxWidth:180,border:true">
                        <!-- 所有角色列表，用户拥有的角色会打勾 -->
                        <table id="roleTable" class="easyui-datagrid" data-options="border:false,fit:true">
                            <thead>
                                <tr>
                                    <th data-options="field:'check',checkbox:true">选择</th>
                                    <th data-options="field:'name',width:150,align:'left'">角色名称</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    
                    <!-- 页面中部 -->
                    <div data-options="region:'center',fit:false,border:false">
                        <div id="layoutTabs" >   
                            <div title="菜单和UI权限">   
                                <!--  页面上部====菜单树 -->
                                <div id="menuPanel" class="easyui-panel" data-options="height:'70%',width:'100%',title:'菜单',border:true">
                                    <table id="menuTree" data-options="border:false">
                                        <thead>
                                            <tr>
                                                <th data-options="field:'name',width:240,align:'left',formatter:menuTreeCheckField">菜单名称</th>
                                                <th data-options="field:'category',width:100,align:'left'">菜单类别</th>
                                                <th data-options="field:'href',width:600,align:'left'">链接</th>
                                                <th data-options="field:'id',width:30,align:'left',hidden:true">编号</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                                <!--  页面下部====UI权限表格 -->
                                <div id="uiPermissionPanel" class="easyui-panel" data-options="height:'30%',width:'100%',title:'当前所选菜单包含的UI权限',border:true">
                                    <table id="uiPermissionTable" class="easyui-datagrid" data-options="border:false,fit:true">
                                        <thead>
                                            <tr>
                                                <th data-options="field:'check',checkbox:true">选择</th>
                                                <th data-options="field:'name',width:200,align:'left'">权限名称</th>
                                                <th data-options="field:'permission',width:150,align:'left'">权限标识字符串</th>
                                                <th data-options="field:'url',width:400,align:'left'">权限对应的请求地址</th>
                                                <th data-options="field:'permissionType',width:80,align:'left',hidden:true">权限类型</th>
                                                <th data-options="field:'menuId',width:150,align:'left',hidden:true">所属菜单</th>
                                                
                                                <th data-options="field:'id',width:30,align:'left',hidden:true">编号</th>
                                                <th data-options="field:'companyId',width:80,align:'left',hidden:true">所属公司的编码</th>
                                                <th data-options="field:'orgId',width:80,align:'left',hidden:true">所属机构的编码</th>
                                                <th data-options="field:'createBy',width:50,align:'left',hidden:true">创建者</th>
                                                <th data-options="field:'createDate',width:100,align:'left',hidden:true">创建时间</th>
                                                <th data-options="field:'updateBy',width:50,align:'left',hidden:true">更新者</th>
                                                <th data-options="field:'updateDate',width:100,align:'left',hidden:true">更新时间</th>
                                                <th data-options="field:'remarks',width:150,align:'left'">备注信息</th>
                                                <th data-options="field:'delFlag',width:50,align:'left',hidden:true">删除标记</th>
                                                <th data-options="field:'uuid',width:80,align:'left',hidden:true">数据UUID</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>   
                            <div title="所有的URL权限">
                                <!-- URL权限表格 -->
                                <div id="allUrlPermissionPanel" class="easyui-panel" data-options="height:'100%',width:'100%',title:'所有的URL权限',border:true">
                                    <table id="allUrlPermissionTable" class="easyui-datagrid" data-options="border:false,fit:true">
                                        <thead>
                                            <tr>
                                                <th data-options="field:'check',checkbox:true">选择</th>
                                                <th data-options="field:'name',width:200,align:'left'">权限名称</th>
                                                <th data-options="field:'permission',width:150,align:'left'">权限标识字符串</th>
                                                <th data-options="field:'url',width:400,align:'left'">权限对应的请求地址</th>
                                                <th data-options="field:'permissionType',width:80,align:'left',hidden:true">权限类型</th>
                                                <th data-options="field:'menuId',width:150,align:'left',hidden:true">所属菜单</th>
                                                
                                                <th data-options="field:'id',width:30,align:'left',hidden:true">编号</th>
                                                <th data-options="field:'companyId',width:80,align:'left',hidden:true">所属公司的编码</th>
                                                <th data-options="field:'orgId',width:80,align:'left',hidden:true">所属机构的编码</th>
                                                <th data-options="field:'createBy',width:50,align:'left',hidden:true">创建者</th>
                                                <th data-options="field:'createDate',width:100,align:'left',hidden:true">创建时间</th>
                                                <th data-options="field:'updateBy',width:50,align:'left',hidden:true">更新者</th>
                                                <th data-options="field:'updateDate',width:100,align:'left',hidden:true">更新时间</th>
                                                <th data-options="field:'remarks',width:150,align:'left'">备注信息</th>
                                                <th data-options="field:'delFlag',width:50,align:'left',hidden:true">删除标记</th>
                                                <th data-options="field:'uuid',width:80,align:'left',hidden:true">数据UUID</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                            <div title="所有的UI权限">
                                <div id="allUiPermissionPanel" class="easyui-panel" data-options="height:'100%',width:'100%',title:'所有的UI权限',border:true">
                                    <table id="allUiPermissionTable" class="easyui-datagrid" data-options="border:false,fit:true">
                                        <thead>
                                            <tr>
                                                <th data-options="field:'check',checkbox:true">选择</th>
                                                <th data-options="field:'name',width:200,align:'left'">权限名称</th>
                                                <th data-options="field:'permission',width:150,align:'left'">权限标识字符串</th>
                                                <th data-options="field:'url',width:400,align:'left'">权限对应的请求地址</th>
                                                <th data-options="field:'permissionType',width:80,align:'left',hidden:true">权限类型</th>
                                                <th data-options="field:'menuId',width:150,align:'left',hidden:true">所属菜单</th>
                                                
                                                <th data-options="field:'id',width:30,align:'left',hidden:true">编号</th>
                                                <th data-options="field:'companyId',width:80,align:'left',hidden:true">所属公司的编码</th>
                                                <th data-options="field:'orgId',width:80,align:'left',hidden:true">所属机构的编码</th>
                                                <th data-options="field:'createBy',width:50,align:'left',hidden:true">创建者</th>
                                                <th data-options="field:'createDate',width:100,align:'left',hidden:true">创建时间</th>
                                                <th data-options="field:'updateBy',width:50,align:'left',hidden:true">更新者</th>
                                                <th data-options="field:'updateDate',width:100,align:'left',hidden:true">更新时间</th>
                                                <th data-options="field:'remarks',width:150,align:'left'">备注信息</th>
                                                <th data-options="field:'delFlag',width:50,align:'left',hidden:true">删除标记</th>
                                                <th data-options="field:'uuid',width:80,align:'left',hidden:true">数据UUID</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div ></div>
    <script type="text/javascript">
    
    // 因为EasyUI TreeGrid控件的BUG(),TreeGrid控件的选择框使用如下方式实现
    var menuTreeCheckIdPrefix = "menuTreeCheckIdPrefix";
    function menuTreeCheckField(value, row, index) {
        var id = menuTreeCheckIdPrefix + row.id;
        var result = $("<div/>");
        var checkbox = $("<input type='checkbox' onclick='menuTreeCheckClick(this)'>");
        checkbox.attr("id", id);

        if(row.check == true) {
            checkbox.prop('checked',true);
        } else {
            checkbox.prop('checked',false);
        }
        result.append(checkbox);
        var span = $("<span class='tree-title'/>");
        span.html(value);
        result.append(span);
        return result.html();
    }
    // 设置菜单树节点选中状态
    function checkRowByMenuTree(id, check) {
        if(check == true) {
            $("#" + menuTreeCheckIdPrefix + id).prop('checked',true);
        } else {
            $("#" + menuTreeCheckIdPrefix + id).prop('checked',false);
        }
    }
    // 设置菜单树所有节点选中状态
    function clearCheckedByMenuTree(check) {
        if(check == true) {
            $("input[type='checkbox'][id*='" + menuTreeCheckIdPrefix + "']").prop('checked',true);
        } else {
            
            $("input[type='checkbox'][id*='" + menuTreeCheckIdPrefix + "']").prop('checked',false);
        }
    }
    // 多选框 选择/取消 事件
    function menuTreeCheckClick(checkbox) {
        var checkbox = $(checkbox);
        var check = checkbox.prop('checked');
        var id = checkbox.attr("id").replace(menuTreeCheckIdPrefix, "");
        if(check == true) {
            // 为角色增加菜单
            var selectRole = $("#roleTable").datagrid("getSelected");
            if(selectRole != null) {
                roleAddMenu(selectRole.id, id, function(success) {
                    if( success == false ) {
                        checkRowByMenuTree(id, false);
                    }
                });
            } else {
                $.messager.alert("提示", "请先选择角色，再为角色增加菜单！", "info");
                checkRowByMenuTree(id, false);
            }
        }
        if(check == false) {
            // 删除角色的菜单
            var selectRole = $("#roleTable").datagrid("getSelected");
            if(selectRole != null) {
                roleDelMenu(selectRole.id, id, function(success) {
                    if( success == false ) {
                        checkRowByMenuTree(id, true);
                    }
                });
            } else {
                $.messager.alert("提示", "请先选择角色，再删除角色的菜单！", "info");
                checkRowByMenuTree(id, true);
            }
        }
    }

    // --------------------------------------------------------------------------------------------------------------
    
    // 查找当前公司的机构
    var findCurrentCompanyOrgUrl = "${pageScope.mvcPath}/sys/findCurrentCompanyOrg";
    // 查找某机构下的直属用户URL
    var findUserByHomeOrgUrl = "${pageScope.mvcPath}/sys/findUserByHomeOrg";
    // 查找当前公司的所有权限
    var findRoleByCurrentCompanyUrl = "${pageScope.mvcPath}/sys/findRoleByCurrentCompany";
    // 根据用户ID得到用户的所有角色信息
    var findRoleByUserIdUrl = "${pageScope.mvcPath}/sys/findRoleByUserId";
    // 为用户增加一个角色
    var userAddRoleUrl = "${pageScope.mvcPath}/sys/userAddRole";
    // 为用户增加所有角色
    var userAddAllRoleUrl = "${pageScope.mvcPath}/sys/userAddAllRole";
    // 为用户删除一个角色
    var userDelRoleUrl = "${pageScope.mvcPath}/sys/userDelRole";
    // 为用户删除所有角色
    var userDelAllRoleUrl = "${pageScope.mvcPath}/sys/userDelAllRole";
    // 获取系统所有菜单
    var getAllMenuUrl = "${pageScope.mvcPath}/sys/getAllMenu";
    // 获取某个菜单的UI权限
    var findUiPermissionByMenuUrl = "${pageScope.mvcPath}/sys/findUiPermissionByMenu";
    // 获取所有的的URL权限
    var findAllUrlPermissionUrl = "${pageScope.mvcPath}/sys/findAllUrlPermission";
    // 获取所有的的UI权限
    var findAllUiPermissionUrl ="${pageScope.mvcPath}/sys/findAllUiPermission";
    // 获取角色拥有的菜单
    var findMenuByRoleIdUrl = "${pageScope.mvcPath}/sys/findMenuByRoleId";
    // 查找某个角色拥有某个菜单下的UI权限
    var findUiPermissionByRoleAndMenuUrl = "${pageScope.mvcPath}/sys/findUiPermissionByRoleAndMenu";
    // 为角色增加菜单
    var roleAddMenuUrl = "${pageScope.mvcPath}/sys/roleAddMenu";
    // 为角色删除菜单
    var roleDelMenuUrl = "${pageScope.mvcPath}/sys/roleDelMenu";
    // 为角色增加权限
    var roleAddPermissionUrl = "${pageScope.mvcPath}/sys/roleAddPermission";
    // 为角色删除权限
    var roleDelPermissionUrl = "${pageScope.mvcPath}/sys/roleDelPermission";
    // 为角色增加所有UI权限
    var roleAddAllUiPermissionUrl = "${pageScope.mvcPath}/sys/roleAddAllUiPermission";
    // 为角色删除所有UI权限
    var roleDelAllUiPermissionUrl = "${pageScope.mvcPath}/sys/roleDelAllUiPermission";
    // 为角色增加所有URL权限
    var roleAddAllUrlPermissionUrl = "${pageScope.mvcPath}/sys/roleAddAllUrlPermission";
    // 为角色删除所有URL权限
    var roleDelAllUrlPermissionUrl = "${pageScope.mvcPath}/sys/roleDelAllUrlPermission";
    // 查找某个角色拥有的所有URL权限
    var findUrlPermissionByRoleIdUrl = "${pageScope.mvcPath}/sys/findUrlPermissionByRoleId";
    // 查找某个角色拥有的所有UI权限
    var findUiPermissionByRoleIdUrl = "${pageScope.mvcPath}/sys/findUiPermissionByRoleId";
    // 为角色增加某个菜单下的所有UI权限
    var roleAddAllUiPermissionByMenuIdUrl = "${pageScope.mvcPath}/sys/roleAddAllUiPermissionByMenuId";
    // 为角色删除某个菜单下的所有UI权限
    var roleDelAllUiPermissionByMenuIdUrl = "${pageScope.mvcPath}/sys/roleDelAllUiPermissionByMenuId";
    
    // roleTable不触发onCheck事件
    var roleTableNotTriggerOnCheck = false;
    // roleTable不触发onUncheck事件
    var roleTableNotTriggerOnUncheck = false;
    // roleTable不触发onCheckAll事件
    var roleTableNotTriggerOnCheckAll = false;
    // roleTable不触发onUnCheckAll事件
    var roleTableNotTriggerOnUnCheckAll = false;
    
    // uiPermissionTable不触发onCheck事件
    var uiPermissionTableNotTriggerOnCheck = false;
    // uiPermissionTable不触发onUncheck事件
    var uiPermissionTableNotTriggerOnUncheck = false;
    // uiPermissionTable不触发onCheckAll事件
    var uiPermissionTableNotTriggerOnCheckAll = false;
    // uiPermissionTable不触发onUnCheckAll事件
    var uiPermissionTableNotTriggerOnUnCheckAll = false;
    
    // allUrlPermissionTable不触发onCheck事件
    var allUrlPermissionTableNotTriggerOncheck = false;
    // allUrlPermissionTable不触发onUncheck事件
    var allUrlPermissionTableNotTriggerOnUncheck = false;
    // allUrlPermissionTable不触发onCheckAll事件
    var allUrlPermissionTableNotTriggerOnCheckAll = false;
    // allUrlPermissionTable不触发onUnCheckAll事件
    var allUrlPermissionTableNotTriggerOnUnCheckAll = false;
    
    // allUiPermissionTable不触发onCheck事件
    var allUiPermissionTableNotTriggerOnCheck = false;
    // allUiPermissionTable不触发onUncheck事件
    var allUiPermissionTableNotTriggerOnUncheck = false;
    // allUiPermissionTable不触发onCheckAll事件
    var allUiPermissionTableNotTriggerOnCheckAll = false;
    // allUiPermissionTable不触发onUnCheckAll事件
    var allUiPermissionTableNotTriggerOnUnCheckAll = false;
    
    // 数据加载等待框被打开的数量
    var loadingDialogCount = 0;
    // 数据加载等待框
    function loadingDialog(stat, text, title) {
        if(stat == "close") {
            if(loadingDialogCount == 1) {
                $.messager.progress("close");
            }
            loadingDialogCount--;
        } else if(stat == "open") {
            loadingDialogCount++;
            if(loadingDialogCount == 1) {
                if(text == undefined || $.trim(text) == "") {
                    text = "正在加载，请稍候...";
                }
                if(title == undefined || $.trim(title) == "") {
                    title = "加载中";
                }
                $.messager.progress({ title : title, text : text });
            }
        } else if(stat == "clear") {
            if(loadingDialogCount >= 1) {
                $.messager.progress("close");
            }
            loadingDialogCount = 0;
        }
        if(loadingDialogCount < 0) {
            loadingDialogCount = 0;
        }
    }
        
    // 加载用户的角色信息
    function loadRoleForUser(successCallback) {
        var roleDate = $("#roleTable").datagrid("getData");
        var selectUser = $("#userTable").datagrid("getSelected");
        if(selectUser == null || roleDate.rows.length <= 0) {
            return ;
        }
        var param = {};
        param.userId = selectUser.id;
        $("#roleTable").datagrid("loading"); // loadingDialog("open");
        $.ajax({
            url : findRoleByUserIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                // 清空选择的角色
                roleTableNotTriggerOnUnCheckAll = true;
                $("#roleTable").datagrid("clearChecked");
                
                // 设置选择的角色
                $(data).each(function (i, userRole) {
                    $(roleDate.rows).each(function (j, role) {
                        if(userRole.id == role.id) {
                            roleTableNotTriggerOnCheck = true;
                            $("#roleTable").datagrid("checkRow", j);
                        }
                    });
                });
                
                // 回调函数
                if($.isFunction(successCallback)) {
                    successCallback();
                }
            },
            complete : function (request, textStatus) {
                $("#roleTable").datagrid("loaded"); // loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                $.messager.alert("操作失败", "加载用户的角色信息失败，请重试！", "error");
                roleTableNotTriggerOnUnCheckAll = true;
                $("#roleTable").datagrid("clearChecked");
            }
        });
    }
    
    // 为用户增加一个角色
    function userAddRole(userId, roleId, callback) {
        var param = {};
        param.userId = userId;
        param.roleId = roleId;
        loadingDialog("open", "正在为用户添加角色...");
        $.ajax({
            url : userAddRoleUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为用户添加角色失败，请重试！", "error");
            }
        });
    }
    
    // 为用户增加所有角色
    function userAddAllRole(userId, callback) {
		var param = {};
        param.userId = userId;
        loadingDialog("open", "正在为用户增加所有角色...");
        $.ajax({
            url : userAddAllRoleUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为用户增加所有角色失败，请重试！", "error");
            }
        });
    }
    
    // 为用户删除一个角色
    function userDelRole(userId, roleId, callback) {
        var param = {};
        param.userId = userId;
        param.roleId = roleId;
        loadingDialog("open", "正在删除用户角色...");
        $.ajax({
            url : userDelRoleUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除用户角色失败，请重试！", "error");
            }
        });
    }
    
    // 为用户删除所有角色
    function userDelAllRole(userId, callback) {
		var param = {};
        param.userId = userId;
        loadingDialog("open", "正在删除用户的所有角色...");
        $.ajax({
            url : userDelAllRoleUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除用户的所有角色失败，请重试！", "error");
            }
        });
    }
    
    // 加载当前角色拥有的菜单信息
    function loadMenuForRole(successCallback) {
        var menuDate = $("#menuTree").treegrid("getData");
        var selectRole = $("#roleTable").datagrid("getSelected");
        if(selectRole == null || menuDate.length <= 0) {
            return ;
        }
        var param = {};
        param.roleId = selectRole.id;
        $("#menuTree").treegrid("loading"); // loadingDialog("open");
        $.ajax({
            url : findMenuByRoleIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                // 清空选择的菜单
                clearCheckedByMenuTree(false);
                
                // 设置选择的菜单
                $(data).each(function (i, roleMenu) {
                    checkRowByMenuTree(roleMenu.id, true);
                });
                
                // 回调函数
                if($.isFunction(successCallback)) {
                    successCallback();
                }
            },
            complete : function (request, textStatus) {
                $("#menuTree").treegrid("loaded"); // loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                $.messager.alert("操作失败", "加载当前角色拥有的菜单信息失败，请重试！", "error");
                clearCheckedByMenuTree(false);
            }
        });
    }
    
    // 加载“当前选择的角色”拥有“当前选择的菜单”下的的UI权限
    function loadUiPermissionForCurrentRoleAndMenu(successCallback) {
        var uiPermissionData = $("#uiPermissionTable").datagrid("getData");
        var selectRole = $("#roleTable").datagrid("getSelected");
        var selectMenu = $("#menuTree").treegrid("getSelected");
        if(selectRole == null || selectMenu == null || uiPermissionData.rows.length <= 0) {
            return ;
        }
        var param = {};
        param.roleId = selectRole.id;
        param.menuId = selectMenu.id;
        $("#uiPermissionTable").datagrid("loading"); // loadingDialog("open");
        $.ajax({
            url : findUiPermissionByRoleAndMenuUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                // 清空菜单下选择的UI权限
                uiPermissionTableNotTriggerOnUnCheckAll = true;
                $("#uiPermissionTable").datagrid("clearChecked");
                
                // 设置菜单下选择的UI权限
                $(data).each(function (i, roleUiPermission) {
                    $(uiPermissionData.rows).each(function (j, uiPermission) {
                        if(roleUiPermission.id == uiPermission.id) {
                            uiPermissionTableNotTriggerOnCheck = true;
                            $("#uiPermissionTable").datagrid("checkRow", j);
                        }
                    });
                });
                
                // 回调函数
                if($.isFunction(successCallback)) {
                    successCallback();
                }
            },
            complete : function (request, textStatus) {
                $("#uiPermissionTable").datagrid("loaded"); // loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                $.messager.alert("操作失败", "加载“当前选择的角色”拥有“当前选择的菜单”下的的UI权限失败，请重试！", "error");
                uiPermissionTableNotTriggerOnUnCheckAll = true;
                $("#uiPermissionTable").datagrid("clearChecked");
            }
        });
    }
    
    // 加载某个角色拥有的URL权限
    function loadUrlPermissionForRole(successCallback) {
        var allUrlPermissionData = $("#allUrlPermissionTable").datagrid("getData");
        var selectRole = $("#roleTable").datagrid("getSelected");
        if(selectRole == null || allUrlPermissionData.rows.leng <= 0) {
            return ;
        }
        var param = {};
        param.roleId = selectRole.id;
        $("#allUrlPermissionTable").datagrid("loading"); // loadingDialog("open");
        $.ajax({
            url : findUrlPermissionByRoleIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                // 清除所有多选框
                allUrlPermissionTableNotTriggerOnUnCheckAll = true;
                $("#allUrlPermissionTable").datagrid("clearChecked");
                
                // 设置多选框
                $(data).each(function (i, roleUrlPermission) {
                    $(allUrlPermissionData.rows).each(function (j, urlPermission) {
                        if(roleUrlPermission.id == urlPermission.id) {
                            allUrlPermissionTableNotTriggerOncheck = true;
                            $("#allUrlPermissionTable").datagrid("checkRow", j);
                        }
                    });
                });
                
                // 回调函数
                if($.isFunction(successCallback)) {
                    successCallback();
                }
            },
            complete : function (request, textStatus) {
                $("#allUrlPermissionTable").datagrid("loaded"); // loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                $.messager.alert("操作失败", "加载“当前选择的角色”拥有的所有URL权限失败，请重试！", "error");
                allUrlPermissionTableNotTriggerOnUnCheckAll = true;
                $("#allUrlPermissionTable").datagrid("clearChecked");
            }
        });
    }
    
    // 加载某个角色拥有的UI权限
    function loadUiPermissionForRole(successCallback) {
        var allUiPermissionData = $("#allUiPermissionTable").datagrid("getData");
        var selectRole = $("#roleTable").datagrid("getSelected");
        if(selectRole == null || allUiPermissionData.rows.leng <= 0) {
            return ;
        }
        var param = {};
        param.roleId = selectRole.id;
        $("#allUiPermissionTable").datagrid("loading"); // loadingDialog("open");
        $.ajax({
            url : findUiPermissionByRoleIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                // 清除所有多选框
                allUiPermissionTableNotTriggerOnUnCheckAll = true;
                $("#allUiPermissionTable").datagrid("clearChecked");
                
                // 设置多选框
                $(data).each(function (i, roleUrlPermission) {
                    $(allUiPermissionData.rows).each(function (j, urlPermission) {
                        if(roleUrlPermission.id == urlPermission.id) {
                            allUiPermissionTableNotTriggerOnCheck = true;
                            $("#allUiPermissionTable").datagrid("checkRow", j);
                        }
                    });
                });
            },
            complete : function (request, textStatus) {
                $("#allUiPermissionTable").datagrid("loaded"); // loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                $.messager.alert("操作失败", "加载“当前选择的角色”拥有的所有UI权限失败，请重试！", "error");
                allUiPermissionTableNotTriggerOnUnCheckAll = true;
                $("#allUiPermissionTable").datagrid("clearChecked");
            }
        });
    }
    
    // 为角色增加菜单
    function roleAddMenu(roleId, menuId, callback) {
        var param = {};
        param.roleId = roleId;
        param.menuId = menuId;
        loadingDialog("open", "正在为角色增加菜单...");
        $.ajax({
            url : roleAddMenuUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为角色增加菜单失败，请重试！", "error");
            }
        });
    }
    
    // 为角色删除菜单
    function roleDelMenu(roleId, menuId, callback) {
        var param = {};
        param.roleId = roleId;
        param.menuId = menuId;
        loadingDialog("open", "正在删除角色的菜单...");
        $.ajax({
            url : roleDelMenuUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除角色的菜单失败，请重试！", "error");
            }
        });
    }
    
    // 为角色增加权限
    function roleAddPermission(roleId, permissionId, callback) {
        var param = {};
        param.roleId = roleId;
        param.permissionId = permissionId;
        loadingDialog("open", "正在为角色增加权限...");
        $.ajax({
            url : roleAddPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为角色增加权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色删除权限
    function roleDelPermission(roleId, permissionId, callback) {
        var param = {};
        param.roleId = roleId;
        param.permissionId = permissionId;
        loadingDialog("open", "正在删除角色权限...");
        $.ajax({
            url : roleDelPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除角色权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色增加所有UI权限
    function roleAddAllUiPermission(roleId, callback) {
        var param = {};
        param.roleId = roleId;
        loadingDialog("open", "正在为角色增加所有UI权限...");
        $.ajax({
            url : roleAddAllUiPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为角色增加所有UI权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色删除所有UI权限
    function roleDelAllUiPermission(roleId, callback) {
        var param = {};
        param.roleId = roleId;
        loadingDialog("open", "正在删除角色所有UI权限...");
        $.ajax({
            url : roleDelAllUiPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除角色所有UI权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色增加所有Url权限
    function roleAddAllUrlPermission(roleId, callback) {
        var param = {};
        param.roleId = roleId;
        loadingDialog("open", "正在为角色增加所有URL权限...");
        $.ajax({
            url : roleAddAllUrlPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为角色增加所有URL权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色删除所有Url权限
    function roleDelAllUrlPermission(roleId, callback) {
        var param = {};
        param.roleId = roleId;
        loadingDialog("open", "正在删除角色所有URL权限...");
        $.ajax({
            url : roleDelAllUrlPermissionUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除角色所有URL权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色增加某个菜单下的所有UI权限
    function roleAddAllUiPermissionByMenuId(roleId, menuId, callback) {
        var param = {};
        param.roleId = roleId;
        param.menuId = menuId;
        loadingDialog("open", "正在为角色增加UI权限...");
        $.ajax({
            url : roleAddAllUiPermissionByMenuIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "为角色增加UI权限失败，请重试！", "error");
            }
        });
    }
    
    // 为角色删除某个菜单下的所有UI权限
    function roleDelAllUiPermissionByMenuId(roleId, menuId, callback) {
        var param = {};
        param.roleId = roleId;
        param.menuId = menuId;
        loadingDialog("open", "正在删除角色UI权限...");
        $.ajax({
            url : roleDelAllUiPermissionByMenuIdUrl,
            data : param,
            async : true,
            type : "POST",
            dataType : 'json',
            success : function (data) {
                if($.isFunction(callback)) {
                    callback(data.success);
                }
                if(data.success == true) {
                    $.messager.show({title : '提示', msg : data.message, timeout : 5000, showType : 'slide'});
                } else {
                    $.messager.alert("操作失败", data.message, "error");
                }
            },
            complete : function (request, textStatus) {
                loadingDialog("close");
            },
            error : function (request, textStatus, errorThrown) {
                // 请求错误处理
                if($.isFunction(callback)) {
                    callback(false);
                }
                $.messager.alert("操作失败", "删除角色UI权限失败，请重试！", "error");
            }
        });
    }
    
    // --------------------------------------------------------------------------------------------------------------
    
    $(document).ready(function() {
        
        // 机构面板设置
        $("#layout001").layout("panel", "west").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    orgTreeRefresh();
                }
            } ]
        });
        
        // 用户面板设置
        $("#layout002").layout("panel", "west").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    userTableRefresh();
                }
            } ]
        });
        
        // 角色面板设置
        $("#layout003").layout("panel", "west").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    roleTableRefresh();
                }
            } ]
        });
        
        // 菜单面板设置
        $("#menuPanel").panel({
            tools : [ {
                iconCls : "ExpandIcon-accept",
                handler : function() {
                    // 全选
                }
            },{
                iconCls : "ExpandIcon-cancel",
                handler : function() {
                    // 全不选
                }
            },{
                iconCls : "icon-reload",
                handler : function() {
                    // 重新加载菜单列表
                    $("#menuTree").treegrid("reload");
                }
            } ]
        });
        
        // 选中菜单下UI权限面板设置
        $("#uiPermissionPanel").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    // 重新加载菜单下UI权限列表
                    $("#uiPermissionTable").datagrid("reload");
                }
            } ]
        });
        
        // 所有的URL权限面板设置
        $("#allUrlPermissionPanel").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    // 重新加载所有的URL权限列表
                    $("#allUrlPermissionTable").datagrid("reload");
                    
                }
            } ]
        });
        
        // 所有的UI权限面板设置
        $("#allUiPermissionPanel").panel({
            tools : [ {
                iconCls : "icon-reload",
                handler : function() {
                    // 重新加载所有的UI权限列表
                    $("#allUiPermissionTable").datagrid("reload");
                }
            } ]
        });
        
        var layoutTabsFirstLoad = true;
        // 菜单权限Tabs
        $("#layoutTabs").tabs({
             fit : true,
             border : false,
             onSelect : function(title,index){
                 if(layoutTabsFirstLoad == true) {
                     layoutTabsFirstLoad = false;
                     return ;
                 }
                 if(title == "所有的UI权限") {
                     // $("#allUiPermissionTable").datagrid("reload");
                     loadUiPermissionForRole();
                 }
             }
        });
        
        // --------------------------------------------------------------------------------------------------------------
        
        // 机构树设置
        $("#orgTree").tree({
            url : findCurrentCompanyOrgUrl,
            method : "post",
            lines : true,
            onSelect : function (node) {
                // 重新加载用户列表
                $("#userTable").datagrid("reload");
                // 清除角色列表的选择
                roleTableNotTriggerOnUnCheckAll = true;
                $("#roleTable").datagrid("clearChecked");
            },
            onLoadError : function() {
                $("#orgTree").tree("loadData", []);
                $.messager.alert("数据加载失败", "加载[机构]信息失败，请重试！", "error");
            }
        });
        // 刷新机构树
        function orgTreeRefresh() {
            // 重新加载机构列表
            $("#orgTree").tree("reload");
            // 清除用户列表
            $("#userTable").datagrid("loadData", { total: 0, rows: [] });
            // 清除角色列表选择
            roleTableNotTriggerOnUnCheckAll = true;
            $("#roleTable").datagrid("clearChecked");
        }
        
        // 用户列表设置
        $("#userTable").datagrid({
            url : findUserByHomeOrgUrl, 
            fit : true,
            fitColumns : true,
            striped : true,
            rownumbers : true,
            singleSelect : true,
            nowrap : true,
            pagination : false,
            loadMsg : "正在加载...",
            onBeforeLoad : function(param) {
                var selectOrg = $("#orgTree").tree("getSelected");
                if(selectOrg == null) {
                    return false;
                }
                param.homeOrg = selectOrg.object.id;
            }, 
            onLoadError : function() {
                $("#userTable").datagrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[用户]数据失败，请重试！", "error");
            },
            onSelect : function(rowIndex, rowData) {
                // 加载用户角色数据
                loadRoleForUser();
            }
        });
        // 刷新用户列表
        function userTableRefresh(){
            // 重新加载用户列表
            $("#userTable").datagrid("reload");
            // 清除角色列表选择
            roleTableNotTriggerOnUnCheckAll = true;
            $("#roleTable").datagrid("clearChecked");
        }
        
        // 角色列表设置
        $("#roleTable").datagrid({
            url : findRoleByCurrentCompanyUrl,
            fit : true,
            fitColumns : true,
            striped : true,
            rownumbers : true,
            nowrap : true,
            singleSelect : true,
            checkOnSelect : false,
            selectOnCheck : false,
            pagination : false,
            loadMsg : "正在加载...",
            onLoadSuccess : function(data){
                loadRoleForUser();
            },
            onLoadError : function() {
                $("#roleTable").datagrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[角色]数据失败，请重试！", "error");
            },
            onSelect : function(rowIndex, rowData) {
                // 加载“当前选择的角色”拥有的菜单
                loadMenuForRole();
                // 加载“当前选择的角色”拥有“当前选择的菜单”下的的UI权限
                loadUiPermissionForCurrentRoleAndMenu();
                // 所有的URL权限
                loadUrlPermissionForRole();
                // 所有的UI权限
                loadUiPermissionForRole();
            },
            onCheck : function(rowIndex, rowData) {
                if(roleTableNotTriggerOnCheck == true) {
                    roleTableNotTriggerOnCheck = false;
                    return ;
                }
                var selectUser = $("#userTable").datagrid("getSelected");
                if(selectUser != null && rowData != null ) {
                    userAddRole(selectUser.id, rowData.id, function(success) {
                        if( success == false ) {
                            roleTableNotTriggerOnUncheck = true;
                            $("#roleTable").datagrid("uncheckRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择用户，再为用户增加角色！", "info");
                    roleTableNotTriggerOnUncheck = true;
                    $("#roleTable").datagrid("uncheckRow", rowIndex);
                }
            },
            onUncheck : function(rowIndex, rowData) {
                if(roleTableNotTriggerOnUncheck == true) {
                    roleTableNotTriggerOnUncheck = false;
                    return ;
                }
                var selectUser = $("#userTable").datagrid("getSelected");
                if(selectUser != null && rowData != null ) {
                    userDelRole(selectUser.id, rowData.id, function(success) {
                        if( success == false ) {
                            roleTableNotTriggerOnCheck = true;
                            $("#roleTable").datagrid("checkRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择用户，再删除用户的角色！", "info");
                    roleTableNotTriggerOnCheck = true;
                    $("#roleTable").datagrid("checkRow", rowIndex);
                }
            },
            onCheckAll : function(rows) {
                if(roleTableNotTriggerOnCheckAll == true) {
                	roleTableNotTriggerOnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectUser = $("#userTable").datagrid("getSelected");
                if(selectUser == null) {
                    $.messager.alert("提示", "请先选择用户，再为用户增加角色！", "info");
                    roleTableNotTriggerOnUnCheckAll = true;
                    $("#roleTable").datagrid("clearChecked");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "为用户增加所有的角色吗？", function (r) {
                    if (r == true ) {
                    	userAddAllRole(selectUser.id, function(success) {
                    		if(success == true) {
                    			roleTableRefresh();
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    roleTableRefresh();
                }
            },
            onUncheckAll : function(rows) {
                if(roleTableNotTriggerOnUnCheckAll == true) {
                    roleTableNotTriggerOnUnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectUser = $("#userTable").datagrid("getSelected");
                if(selectUser == null) {
                    $.messager.alert("提示", "请先选择用户，再删除用户的角色！", "info");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "删除用户所有的角色吗？", function (r) {
                    if (r == true ) {
                    	userDelAllRole(selectUser.id, function(success) {
                    		if(success == true) {
                    			roleTableRefresh();
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    roleTableRefresh();
                }
            }
        });
        // 刷新角色列表
        function roleTableRefresh(){
            // 重新加载角色列表
            $("#roleTable").datagrid("reload");
            // 清除菜单的选择
            clearCheckedByMenuTree(false);
            // 清除权限列表的选择
            uiPermissionTableNotTriggerOnUnCheckAll = true;
            $("#uiPermissionTable").datagrid("clearChecked");
            allUrlPermissionTableNotTriggerOnUnCheckAll = true;
            $("#allUrlPermissionTable").datagrid("clearChecked");
            allUiPermissionTableNotTriggerOnUnCheckAll = true;
            $("#allUiPermissionTable").datagrid("clearChecked");
        }
        
        var selectMenu = null;
        // 设置菜单树设置
        $("#menuTree").treegrid({
            url : getAllMenuUrl,
            idField: 'id',
            treeField: 'name',
            fit : true,
            fitColumns : false,
            striped : true,
            rownumbers : true,
            nowrap : true,
            singleSelect : true,
            checkOnSelect : false,
            selectOnCheck : false,
            pagination : false,
            loadMsg : "正在加载...", 
            onLoadSuccess : function(data){
                loadMenuForRole();
            },
            onLoadError : function() {
                $("#roleTable").treegrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[菜单]数据失败，请重试！", "error");
            },
            onSelect : function(rowIndex, rowData) {
                var currentMenu = $("#menuTree").treegrid("getSelected");
                if(selectMenu != null && currentMenu != null && selectMenu.id == currentMenu.id) {
                    return ;
                }
                selectMenu = currentMenu;
                // 加载当前选择的菜单所有的UI权限,当加载成功立即加载“当前选择的角色”拥有“当前选择的菜单”下的的UI权限
                $("#uiPermissionTable").datagrid("reload");
            }
        });
        
        // 选中菜单下的UI权限表格设置
        $("#uiPermissionTable").datagrid({
            url : findUiPermissionByMenuUrl,
            fit : true,
            fitColumns : false,
            striped : true,
            rownumbers : true,
            nowrap : true,
            singleSelect : true,
            checkOnSelect : false,
            selectOnCheck : false,
            pagination : false,
            loadMsg : "正在加载...", 
            onBeforeLoad : function(param) {
                var selectMenu = $("#menuTree").treegrid("getSelected");
                if(selectMenu == null) {
                    return false;
                }
                param.menuId = selectMenu.id;
            }, 
            onLoadSuccess : function(data){
                loadUiPermissionForCurrentRoleAndMenu();
            },
            onLoadError : function() {
                $("#uiPermissionTable").datagrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[当前所选菜单包含的UI权限]数据失败，请重试！", "error");
            },
            onCheck : function(rowIndex, rowData) {
                if(uiPermissionTableNotTriggerOnCheck == true) {
                    uiPermissionTableNotTriggerOnCheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                var selectMenu = $("#menuTree").treegrid("getSelected");
                if(selectRole != null && rowData != null && selectMenu != null) {
                    roleAddPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            uiPermissionTableNotTriggerOnUncheck = true;
                            $("#uiPermissionTable").datagrid("uncheckRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色和菜单，再为角色增加UI权限！", "info");
                    uiPermissionTableNotTriggerOnUncheck = true;
                    $("#uiPermissionTable").datagrid("uncheckRow", rowIndex);
                }
            },
            onUncheck : function(rowIndex, rowData) {
                if(uiPermissionTableNotTriggerOnUncheck == true) {
                    uiPermissionTableNotTriggerOnUncheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                var selectMenu = $("#menuTree").treegrid("getSelected");
                if(selectRole != null && rowData != null && selectMenu != null) {
                    roleDelPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            uiPermissionTableNotTriggerOnCheck = true;
                            $("#uiPermissionTable").datagrid("checkRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色和菜单，再为角色删除UI权限！", "info");
                    uiPermissionTableNotTriggerOnCheck = true;
                    $("#uiPermissionTable").datagrid("checkRow", rowIndex);
                }
            },
            onCheckAll : function(rows) {
                if(uiPermissionTableNotTriggerOnCheckAll == true) {
                	uiPermissionTableNotTriggerOnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                var selectMenu = $("#menuTree").treegrid("getSelected");
                if(selectRole == null || selectMenu == null) {
                    $.messager.alert("提示", "请先选择角色和菜单，再为角色增加UI权限！", "info");
                    uiPermissionTableNotTriggerOnUnCheckAll = true;
                    $("#uiPermissionTable").datagrid("clearChecked");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "为角色增加该菜单下的所有权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleAddAllUiPermissionByMenuId(selectRole.id, selectMenu.id, function(success){
                    		if(success==true) {
                    			$("#uiPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#uiPermissionTable").datagrid("reload");
                }
            },
            onUncheckAll : function(rows) {
                if(uiPermissionTableNotTriggerOnUnCheckAll == true) {
                    uiPermissionTableNotTriggerOnUnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                var selectMenu = $("#menuTree").treegrid("getSelected");
                if(selectRole == null || selectMenu == null) {
                    $.messager.alert("提示", "请先选择角色和菜单，再为角色删除UI权限！", "info");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "删除角色在该菜单下的所有权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleDelAllUiPermissionByMenuId(selectRole.id, selectMenu.id, function(success){
                    		if(success==true) {
                    			$("#uiPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#uiPermissionTable").datagrid("reload");
                }
            }
        });
        
        // 所有的URL权限表格设置
        $("#allUrlPermissionTable").datagrid({
            url : findAllUrlPermissionUrl,
            fit : true,
            fitColumns : false,
            striped : true,
            rownumbers : true,
            nowrap : true,
            singleSelect : true,
            checkOnSelect : false,
            selectOnCheck : false,
            pagination : false,
            loadMsg : "正在加载...", 
            onLoadSuccess : function(data){
                loadUrlPermissionForRole();
            },
            onLoadError : function() {
                $("#allUrlPermissionTable").datagrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[所有的URL权限]数据失败，请重试！", "error");
            },
            onCheck : function(rowIndex, rowData) {
                if(allUrlPermissionTableNotTriggerOncheck == true) {
                    allUrlPermissionTableNotTriggerOncheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                if(selectRole != null && rowData != null) {
                    roleAddPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            allUrlPermissionTableNotTriggerOnUncheck = true;
                            $("#allUrlPermissionTable").datagrid("uncheckRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色，再为角色增加URL权限！", "info");
                    allUrlPermissionTableNotTriggerOnUncheck = true;
                    $("#allUrlPermissionTable").datagrid("uncheckRow", rowIndex);
                }
            },
            onUncheck : function(rowIndex, rowData) {
                if(allUrlPermissionTableNotTriggerOnUncheck == true) {
                    allUrlPermissionTableNotTriggerOnUncheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                if(selectRole != null && rowData != null) {
                    roleDelPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            allUrlPermissionTableNotTriggerOncheck = true;
                            $("#allUrlPermissionTable").datagrid("checkRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色，再删除角色的URL权限！", "info");
                    allUrlPermissionTableNotTriggerOncheck = true;
                    $("#allUrlPermissionTable").datagrid("checkRow", rowIndex);
                }
            },
            onCheckAll : function(rows) {
                if(allUrlPermissionTableNotTriggerOnCheckAll == true) {
                	allUrlPermissionTableNotTriggerOnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                if(selectRole == null) {
                    $.messager.alert("提示", "请先选择角色，再为角色增加URL权限！", "info");
                    allUrlPermissionTableNotTriggerOnUnCheckAll = true;
                    $("#allUrlPermissionTable").datagrid("clearChecked");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "为角色增加所有的URL权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleAddAllUrlPermission(selectRole.id, function(success) {
                    		if(success == true) {
                    			$("#allUrlPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#allUrlPermissionTable").datagrid("reload");
                }
            },
            onUncheckAll : function(rows) {
                if(allUrlPermissionTableNotTriggerOnUnCheckAll == true) {
                    allUrlPermissionTableNotTriggerOnUnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                if(selectRole == null) {
                    $.messager.alert("提示", "请先选择角色，再删除角色的URL权限！", "info");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "删除角色所有的URL权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleDelAllUrlPermission(selectRole.id, function(success) {
                    		if(success == true) {
                    			$("#allUrlPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#allUrlPermissionTable").datagrid("reload");
                }
            }
        });
        
        // 所有的UI权限表格设置
        $("#allUiPermissionTable").datagrid({
            url : findAllUiPermissionUrl,
            fit : true,
            fitColumns : false,
            striped : true,
            rownumbers : true,
            nowrap : true,
            singleSelect : true,
            checkOnSelect : false,
            selectOnCheck : false,
            pagination : false,
            loadMsg : "正在加载...", 
            onLoadSuccess : function(data){
                loadUiPermissionForRole();
            },
            onLoadError : function() {
                $("#allUiPermissionTable").datagrid("loadData", { total: 0, rows: [] });
                $.messager.alert("数据加载失败", "加载[所有的UI权限]数据失败，请重试！", "error");
            },
            onCheck : function(rowIndex, rowData) {
                if(allUiPermissionTableNotTriggerOnCheck == true) {
                    allUiPermissionTableNotTriggerOnCheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                if(selectRole != null && rowData != null) {
                    roleAddPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            allUiPermissionTableNotTriggerOnUncheck = true;
                            $("#allUiPermissionTable").datagrid("uncheckRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色，再为角色增加UI权限！", "info");
                    allUiPermissionTableNotTriggerOnUncheck = true;
                    $("#allUiPermissionTable").datagrid("uncheckRow", rowIndex);
                }
            },
            onUncheck : function(rowIndex, rowData) {
                if(allUiPermissionTableNotTriggerOnUncheck == true) {
                    allUiPermissionTableNotTriggerOnUncheck = false;
                    return ;
                }
                if(allUrlPermissionTableNotTriggerOnUncheck == true) {
                    allUrlPermissionTableNotTriggerOnUncheck = false;
                    return ;
                }
                var selectRole = $("#roleTable").treegrid("getSelected");
                if(selectRole != null && rowData != null) {
                    roleDelPermission(selectRole.id, rowData.id, function(success){
                        if( success == false ) {
                            allUiPermissionTableNotTriggerOnCheck = true;
                            $("#allUiPermissionTable").datagrid("checkRow", rowIndex);
                        }
                    });
                } else {
                    $.messager.alert("提示", "请先选择角色，再删除角色的UI权限！", "info");
                    allUiPermissionTableNotTriggerOnCheck = true;
                    $("#allUiPermissionTable").datagrid("checkRow", rowIndex);
                }
            },
            onCheckAll : function(rows) {
                if(allUiPermissionTableNotTriggerOnCheckAll == true) {
                	allUiPermissionTableNotTriggerOnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                if(selectRole == null) {
                    $.messager.alert("提示", "请先选择角色，再为角色增加UI权限！", "info");
                    allUiPermissionTableNotTriggerOnUnCheckAll = true;
                    $("#allUiPermissionTable").datagrid("clearChecked");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "为角色增加所有的UI权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleAddAllUiPermission(selectRole.id, function(success) {
                    		if(success == true) {
                    			$("#allUiPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#allUiPermissionTable").datagrid("reload");
                }
            },
            onUncheckAll : function(rows) {
                if(allUiPermissionTableNotTriggerOnUnCheckAll == true) {
                    allUiPermissionTableNotTriggerOnUnCheckAll = false;
                    return ;
                }
                if(rows.length <= 0) {
                    $.messager.alert("提示", "当前表格没有数据，不能全选！", "info");
                    return ;
                }
                var selectRole = $("#roleTable").datagrid("getSelected");
                if(selectRole == null) {
                    $.messager.alert("提示", "请先选择角色，再删除角色的UI权限！", "info");
                    return ;
                }
                var cancel = false;
                $.messager.confirm("确认对话框", "删除角色所有的UI权限吗？", function (r) {
                    cancel = r;
                    if (r == true ) {
                    	roleDelAllUiPermission(selectRole.id, function(success) {
                    		if(success == true) {
                    			$("#allUiPermissionTable").datagrid("reload");
                    		}
                    	});
                    }
                });
                if(cancel == false) {
                    $("#allUiPermissionTable").datagrid("reload");
                }
            }
        });
    });
    </script>
</body>
</html>